package crossover;

import java.util.ArrayList;
import java.util.Random;

import model.Chromosome;

public class SinglePoint extends Crossover {
	
	Random rand=new Random();
	
	public SinglePoint(double crossoverRate) {
		this.crossoverRate=crossoverRate;
	}
	
	@Override
	public Chromosome[] crossover(Chromosome[] parents) {
		int size=parents[0].getChromosome().size();
		double rate= rand.nextDouble()*100;
		int index = rand.nextInt(size);
		if(rate>crossoverRate)
		{
			ArrayList<Integer> ch1=new ArrayList<Integer>(), ch2=new ArrayList<Integer>();
			
			for(int i=0; i<=index ;++i)
			{
				ch1.add(parents[0].getChromosome().get(i));
				ch2.add(parents[1].getChromosome().get(i));
			}
			for(int i=0; i<size; ++i)
			{
				if(!existNumInCh(ch1,parents[1].getChromosome().get(i)))
					ch1.add(parents[1].getChromosome().get(i));
				if(!existNumInCh(ch2,parents[0].getChromosome().get(i)))
					ch2.add(parents[0].getChromosome().get(i));
			}
	
			Chromosome[] child = { new Chromosome(ch1), new Chromosome(ch2) };
			return child;
		}
		else 
			return parents;
	}
	private boolean existNumInCh(ArrayList<Integer> ch2, int num) {
		for (Integer integer : ch2) {
			if(integer.intValue()==num)
				return true;
		}
		return false;
	}

	@Override
	public String toString() {
		return "SinglePoint";
	}

}
